package test.android;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.util.Config;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

public class FragmentTakePicture extends DialogFragment{
	private static final int ACTION_GET_PICTURE = 0x11;
	private static final String PATH = Environment.getExternalStorageDirectory().toString() + "/LIVEREPORT";
	
	View mainLayout;
	File tempFile;
	Activity mActivity;
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mActivity = activity;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setStyle(STYLE_NORMAL, android.R.style.Theme_Translucent_NoTitleBar);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mainLayout = inflater.inflate(R.layout.fragment_take_picture, container, false);
		initGUI();
		return mainLayout;
	}
	
	public void initGUI() {
		File file = new File(PATH);
		if (!file.exists()) {
			file.mkdir();
		}		
		
		mainLayout.findViewById(R.id.btn_take_picture).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				takePicture();
			}
		});
		
		mainLayout.findViewById(R.id.btn_open_gallery).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openGallery();
			}
		});
		
	}
	
    public void takePicture() {
    	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    	tempFile = createFile();
    	intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
    	startActivityForResult(intent, ACTION_GET_PICTURE);
    }	

    public File createFile() {
    	String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    	return new File(PATH, fileName + ".jpg");
    }
    
    public void openGallery() {
    	Intent intent = new Intent();
    	intent.setAction(Intent.ACTION_GET_CONTENT);
    	intent.setType("image/*");
    	startActivityForResult(intent, ACTION_GET_PICTURE);
    }    
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	if (resultCode == Activity.RESULT_OK) {
	    	if (requestCode == ACTION_GET_PICTURE) {
	    		handleTakenImage(data);
	    	}
    	}
    }
	
    public void handleTakenImage(Intent intent) {
    	Uri imageUri = intent.getData();
    	String imagePath = "";
    	
    	if (imageUri.toString().startsWith("file")) { // photo from camera, start with file:///..
    		imagePath = imageUri.getPath();
    	} else if (imageUri.toString().startsWith("content")) {								 // photo from gallery, start with content://..
        	// get path of image
        	String[] column = {MediaStore.Images.Media.DATA};
        	Cursor cursor = mActivity.getContentResolver().query(imageUri, column, null, null, null);
        	cursor.moveToFirst();
        	imagePath = cursor.getString(0);
        	cursor.close();
    	}
    	
    	Bitmap resizedBitmap = Utils.resizeBitmap(imagePath, 720);
    	Bitmap rotatedBitmap;	
    	
    	int rotate = getCameraPhotoOrientation(mActivity, imageUri, imagePath);
    	if (rotate != 0) {
    		Matrix matrix = new Matrix();
    		matrix.postRotate(rotate);
    		rotatedBitmap = Bitmap.createBitmap(resizedBitmap, 0, 0, resizedBitmap.getWidth(), resizedBitmap.getHeight(), matrix, false);
    	} else {
    		rotatedBitmap = resizedBitmap;
    	}
    	
    	ImageView imageView = (ImageView) mainLayout.findViewById(R.id.img);
    	if (rotatedBitmap != null) {
    		imageView.setImageBitmap(rotatedBitmap);
    	}    	
    	Log.e("stk", "resized bitmap=" + resizedBitmap.getWidth() + "x" + resizedBitmap.getHeight());
    	Log.e("stk", "rotated bitmap=" + rotatedBitmap.getWidth() + "x" + rotatedBitmap.getHeight());
    	
    	File file = new File(PATH, "XXX.jpg");
    	Utils.saveBitmapToFile(rotatedBitmap, file.toString());
    	Log.e("stk", "saved filepath=" + file.toString());
    }	
    
    
	public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath) {
		int rotate = 0;
		try {
//			context.getContentResolver().notifyChange(imageUri, null);
			File imageFile = new File(imagePath);
			ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
			int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_270:
				rotate = 270;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				rotate = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_90:
				rotate = 90;
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.e("stk", "rotate=" + rotate);
		return rotate;
	}    
	
	
}
